package com.example.myapplication;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.hardware.camera2.CameraManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.util.Locale;

public class MainActivity extends AppCompatActivity {
    private static final int PERMISSION_REQUEST_CODE = 123;
    private CameraManager cameraManager;
    private String cameraId;
    private boolean isFlashOn = false;
    private int currentLanguage = 0; // 0: 简体中文, 1: 繁体中文, 2: 英文, 3: 日文
    private boolean isPortrait = true;
    private Button btnFlashlight, btnDouyin, btnCall, btnLanguage, btnOrientation, btnColor;
    private int currentColor = Color.parseColor("#4ECDC4");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 初始化相机管理器
        cameraManager = (CameraManager) getSystemService(CAMERA_SERVICE);
        try {
            cameraId = cameraManager.getCameraIdList()[0];
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 初始化按钮
        btnFlashlight = findViewById(R.id.btnFlashlight);
        btnDouyin = findViewById(R.id.btnDouyin);
        btnCall = findViewById(R.id.btnCall);
        btnLanguage = findViewById(R.id.btnLanguage);
        btnOrientation = findViewById(R.id.btnOrientation);
        btnColor = findViewById(R.id.btnColor);

        // 设置按钮点击事件
        btnFlashlight.setOnClickListener(v -> {
            animateButton(v);
            toggleFlashlight();
        });
        btnDouyin.setOnClickListener(v -> {
            animateButton(v);
            openDouyin();
        });
        btnCall.setOnClickListener(v -> {
            animateButton(v);
            makePhoneCall();
        });
        btnLanguage.setOnClickListener(v -> {
            animateButton(v);
            showLanguageDialog();
        });
        btnOrientation.setOnClickListener(v -> {
            animateButton(v);
            toggleOrientation();
        });
        btnColor.setOnClickListener(v -> {
            animateButton(v);
            showColorPickerDialog();
        });

        // 添加屏幕旋转监听
        getWindow().getDecorView().setOnApplyWindowInsetsListener((v, insets) -> {
            Configuration configuration = getResources().getConfiguration();
            if (configuration.orientation == Configuration.ORIENTATION_LANDSCAPE) {
                isPortrait = false;
                updateButtonLayout();
            } else {
                isPortrait = true;
                updateButtonLayout();
            }
            return insets;
        });
    }

    private void showColorPickerDialog() {
        View dialogView = LayoutInflater.from(this).inflate(R.layout.color_picker_dialog, null);
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setView(dialogView)
                .create();

        int[] colorIds = {
                R.id.btnColor1, R.id.btnColor2, R.id.btnColor3, R.id.btnColor4,
                R.id.btnColor5, R.id.btnColor6, R.id.btnColor7, R.id.btnColor8
        };

        int[] colors = {
                Color.parseColor("#4ECDC4"), Color.parseColor("#FF6B6B"),
                Color.parseColor("#45B7D1"), Color.parseColor("#96CEB4"),
                Color.parseColor("#FFEEAD"), Color.parseColor("#D4A5A5"),
                Color.parseColor("#9B59B6"), Color.parseColor("#3498DB")
        };

        for (int i = 0; i < colorIds.length; i++) {
            Button colorBtn = dialogView.findViewById(colorIds[i]);
            int finalI = i;
            colorBtn.setOnClickListener(v -> {
                currentColor = colors[finalI];
                updateButtonColors();
                dialog.dismiss();
            });
        }

        dialog.show();
    }

    private void updateButtonColors() {
        int[] buttonIds = {
                R.id.btnFlashlight, R.id.btnDouyin, R.id.btnCall,
                R.id.btnLanguage, R.id.btnOrientation, R.id.btnColor
        };

        for (int id : buttonIds) {
            Button button = findViewById(id);
            button.setBackgroundTintList(android.content.res.ColorStateList.valueOf(currentColor));
        }
    }

    private void animateButton(View view) {
        Animation scaleAnimation = AnimationUtils.loadAnimation(this, android.R.anim.fade_in);
        scaleAnimation.setDuration(100);
        view.startAnimation(scaleAnimation);
    }

    private void updateButtonLayout() {
        if (!isPortrait) {
            // 横屏布局调整
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT
            );
            params.setMargins(16, 16, 16, 16);
            btnOrientation.setLayoutParams(params);
            btnColor.setLayoutParams(params);
        } else {
            // 竖屏布局调整
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT
            );
            params.setMargins(16, 16, 16, 16);
            btnOrientation.setLayoutParams(params);
            btnColor.setLayoutParams(params);
        }
    }

    private void toggleFlashlight() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.CAMERA},
                    PERMISSION_REQUEST_CODE);
            return;
        }

        try {
            cameraManager.setTorchMode(cameraId, !isFlashOn);
            isFlashOn = !isFlashOn;
            Toast.makeText(this, isFlashOn ? "手电筒已打开" : "手电筒已关闭", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "无法控制手电筒", Toast.LENGTH_SHORT).show();
        }
    }

    private void openDouyin() {
        try {
            // 尝试使用抖音的包名打开
            Intent intent = new Intent();
            intent.setPackage("com.ss.android.ugc.aweme");
            intent.setAction(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            
            // 如果抖音未安装，则跳转到应用商店
            if (intent.resolveActivity(getPackageManager()) == null) {
                intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(Uri.parse("market://details?id=com.ss.android.ugc.aweme"));
                // 如果应用商店未安装，则使用浏览器打开
                if (intent.resolveActivity(getPackageManager()) == null) {
                    intent.setData(Uri.parse("https://play.google.com/store/apps/details?id=com.ss.android.ugc.aweme"));
                }
            }
            startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, getString(R.string.douyin_not_installed), Toast.LENGTH_SHORT).show();
        }
    }

    private void makePhoneCall() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.CALL_PHONE},
                    PERMISSION_REQUEST_CODE);
            return;
        }

        Intent intent = new Intent(Intent.ACTION_CALL);
        intent.setData(Uri.parse("tel:15034002004"));
        startActivity(intent);
    }

    private void showLanguageDialog() {
        String[] languages = {
            getString(R.string.simplified_chinese),
            getString(R.string.traditional_chinese),
            getString(R.string.english),
            getString(R.string.japanese)
        };

        new AlertDialog.Builder(this)
            .setTitle(R.string.select_language)
            .setItems(languages, (dialog, which) -> {
                currentLanguage = which;
                changeLanguage();
            })
            .show();
    }

    private void changeLanguage() {
        Locale locale;
        switch (currentLanguage) {
            case 0:
                locale = Locale.SIMPLIFIED_CHINESE;
                break;
            case 1:
                locale = Locale.TRADITIONAL_CHINESE;
                break;
            case 2:
                locale = Locale.ENGLISH;
                break;
            case 3:
                locale = Locale.JAPANESE;
                break;
            default:
                locale = Locale.SIMPLIFIED_CHINESE;
        }

        Resources resources = getResources();
        Configuration configuration = resources.getConfiguration();
        configuration.setLocale(locale);
        resources.updateConfiguration(configuration, resources.getDisplayMetrics());

        // 重启活动以应用新的语言设置
        Intent intent = new Intent(this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
    }

    private void toggleOrientation() {
        if (isPortrait) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
        isPortrait = !isPortrait;
    }
}